import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
import { ElMessage } from 'element-plus';

import { useAuthStore } from '@/store';
import qs from 'qs';
import { Session } from './storage';

// 配置新建一个 axios 实例
const service = axios.create({
    baseURL: '/apis',
    timeout: 50000
});

let errorTokenInvalid = false;
interface AxiosRequestConfigInterface extends AxiosRequestConfig, Service.RequestParam {}

// 添加请求拦截器
service.interceptors.request.use(
    (config: AxiosRequestConfigInterface) => {
        const contentTypeForm = ['post', 'put'].includes(config.method as string);

        // 在发送请求之前做些什么 token
        if (Session.get('token')) {
            (<any>config.headers).Authorization = `Bearer ${Session.get('token')}`;
        }
        if (contentTypeForm) {
            if (config.isJsonType) {
                (<any>config.headers)['content-type'] = ` application/json;charset=UTF-8`;
            } else {
                (<any>config.headers)['content-type'] = `application/x-www-form-urlencoded; charset=UTF-8`;
                config.data = qs.stringify(config.data);
            }
        }
        return config;
    },
    error => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
service.interceptors.response.use(
    response => {
        // 对响应数据做点什么
        const res = response.data;
        // res.code = 1009;

        if (res?.code === 200) {
            return Promise.resolve(response.data.data);
        }

        // token失效，重置auth状态
        if (res.code === 1009 && !errorTokenInvalid) {
            ElMessage.error('身份过期，请重新登录 ');
            errorTokenInvalid = true;
            const { resetAuthStore } = useAuthStore();
            resetAuthStore();
        } else {
            ElMessage.error(res.msg);
            return Promise.reject(res.msg);
        }
    },
    error => {
        // 对响应错误做点什么
        if (error.message.indexOf('timeout') !== -1) {
            ElMessage.error('网络超时');
        } else if (error.message === 'Network Error') {
            ElMessage.error('网络连接错误');
        } else if (error.response.data) ElMessage.error(error.response.statusText);
        else ElMessage.error('接口路径找不到');
        return Promise.reject(error);
    }
);

// 导出 axios 实例
export default service;
